//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.Mail;
using CommunityServer;
using CommunityServer.Components;

namespace CommunityServer.Blogs.Components
{
	/// <summary>
	/// Summary description for WeblogEmails.
	/// </summary>
	internal class WeblogEmails : Emails
	{
		private WeblogEmails()
		{
			
		}

		public static void WeblogTracking(WeblogPost post, WeblogPost parent)
		{
			if (post.IsFeedback && parent == null)
				return;

			SectionTracking(post, new EnquePostEmails(CreateWeblogPost), CreatePostFormatList(post.Weblog, post, parent) );
		}

		public static void WeblogFeedbackNotification(WeblogPost post, WeblogPost parent)
		{
			if (post.IsFeedback && parent == null)
				return;

			string postUserName = "";
			if (!Globals.IsNullorEmpty(post.Username))
				postUserName = post.Username;
			else if ( (post.User != null) && (!Globals.IsNullorEmpty(post.User.Username)) )
				postUserName = post.User.Username;
			
			if (parent.EnableAllOwnerNotification && !Globals.IsNullorEmpty(post.Weblog.Owners))
			{
				// Loop through each owner and send the notification email if that owner was 
				//	not the one who posted the feedback item.
				foreach(string username in post.Weblog.OwnerArray)
				{
					User owner = Users.FindUserByUsername(username);
					if ( !Globals.IsNullorEmpty(owner.Email) && (owner.Username != postUserName) )
					{
						MailMessage email = CreateWeblogFeedbackNotification(post, owner, CreatePostFormatList(post.Weblog, post, parent) );

						if(email != null && email.To != null && email.To.Trim().Length > 0)
							EmailQueueProvider.Instance().QueueEmail(email);
					}
				}
			}
			else
			{
				// Send notification email to the author of the thread if he/she was not the one who posted the feedback item.
				User owner = Users.FindUserByUsername(parent.Username);
				if ( !Globals.IsNullorEmpty(owner.Email) && (owner.Username != postUserName) )
				{
					MailMessage email = CreateWeblogFeedbackNotification(post, owner, CreatePostFormatList(post.Weblog, post, parent) );

					if(email != null && email.To != null && email.To.Trim().Length > 0)
						EmailQueueProvider.Instance().QueueEmail(email);
				}
			}

		}

		public static void WeblogFeedbackModerationThresholdNotification(Weblog blog)
		{
			// Loop through each owner and send the notification email
			foreach (string username in blog.OwnerArray)
			{
				User owner = Users.FindUserByUsername(username);
				if (owner != null && !Globals.IsNullorEmpty(owner.Email))
				{
					MailMessage email = CreatFeedbackModerationThresholdNotification(blog, owner, CreateBlogFormatList(blog));

					if (email != null && email.To != null && email.To.Trim().Length > 0)
						EmailQueueProvider.Instance().QueueEmail(email);
				}
			}
		}

		private static FormatList CreatePostFormatList(Weblog weblog, WeblogPost post, WeblogPost parent)
		{
			FormatList list = new FormatList();
			BlogUrls urls = BlogUrls.Instance();

			list.Add("blogName", weblog.Name);
			list.Add("blogUrl", Globals.FullPath(urls.HomePage(weblog.ApplicationKey)));
			list.Add("postedBy", post.DisplayName);

			CSContext cntx = CSContext.Current;

			list.Add("postedDate", post.UserTime.ToString("f"));
			list.Add("Title", post.Subject);
			list.Add("subscriptionLink", Globals.FullPath(urls.EmailSubscriptions(weblog.ApplicationKey)));
			list.Add("adminemailfrom", string.Format(ResourceManager.GetString("AutomatedEmail").Trim(), cntx.SiteSettings.SiteName, cntx.SiteSettings.AdminEmailAddress));


			if (parent != null)
			{
				list.Add("postLink", Globals.FullPath(urls.Post(parent, weblog, post)));
				list.Add("titleUrl", post.TitleUrl);
				list.Add("originalPostName", parent.Subject);
			}
			else
			{
				list.Add("postLink", Globals.FullPath(urls.Post(post, weblog)));
			}

			list.Add("feedbackType", post.BlogPostTypeName);
			if (post.IsApproved)
				list.Add("publishedStatus", ResourceManager.GetString("Post_IsApproved"));
			else
				list.Add("publishedStatus", ResourceManager.GetString("Post_NotApproved"));


			if ((post.PostStatus & PostStatus.Spam) == PostStatus.Spam)
				list.Add("spamStatus", "[Spam] ");
			else if ((post.PostStatus & PostStatus.LikelySpam) == PostStatus.LikelySpam)
				list.Add("spamStatus", "[Possible Spam] ");
			else
				list.Add("spamStatus", string.Empty);

			list.Add("spamScore", post.SpamScore.ToString());


			list.Add("approve", Globals.FullPath(urls.AdminFeedbackAction(weblog.SectionID, "approve", post.PostID)));
			list.Add("moderate", Globals.FullPath(urls.AdminFeedbackAction(weblog.SectionID, "moderate", post.PostID)));
			list.Add("delete", Globals.FullPath(urls.AdminFeedbackAction(weblog.SectionID, "delete", post.PostID)));


			return list;
		}
		
		private static FormatList CreateBlogFormatList(Weblog weblog)
        {
            FormatList list = new FormatList();
            BlogUrls urls = BlogUrls.Instance();
			CSContext cntx = CSContext.Current;

            list.Add("blogName", weblog.Name);
            list.Add("blogUrl", Globals.FullPath(urls.HomePage(weblog.ApplicationKey)));
            list.Add("adminemailfrom", string.Format( ResourceManager.GetString("AutomatedEmail").Trim(), cntx.SiteSettings.SiteName, cntx.SiteSettings.AdminEmailAddress));

			list.Add("postsToModerate", weblog.PostsToModerate.ToString());
			list.Add("moderatedFeedbackNotificationThreshold", weblog.ModeratedFeedbackNotificationThreshold.ToString());
			list.Add("adminFeedbackLink", Globals.FullPath(urls.AdminFeedback(weblog.SectionID)));
            
            return list;
        }

		private static MailMessage CreateWeblogPost(Post post, User user, FormatList formats)
		{
			string emailType = null;
			if(post.ParentID > 0)
			{
				emailType = "WeblogComment";
			}
			else
			{
				emailType = "WeblogNewPost";
			}
			MailMessage email = GenericEmail(emailType,user,null,null,false,user.EnableHtmlEmail);

			if(email == null)
				return null;

			email.From = formats.Format(email.From);
			email.Body = formats.Format(email.Body);
			email.Subject = formats.Format(email.Subject);
			email.To = user.Email;
			
			string postbody = null;

			// if the user doesn't want HTML and the post is HTML, then strip it
			if (!user.EnableHtmlEmail && post.PostType == PostContentType.HTML) 
				postbody = Emails.FormatHtmlAsPlainText(post.RenderedBody(PostTarget.Other));
			else
				postbody =  post.RenderedBody(PostTarget.Other);
				
			postbody.Trim();

			email.Body = FormatList.Format(email.Body, "postbody", postbody);


			
			return email;
		}

		private static MailMessage CreateWeblogFeedbackNotification(Post post, User user, FormatList formats)
		{

			MailMessage email = GenericEmail("WeblogFeedbackNotification", user, null, null, false, user.EnableHtmlEmail);

			if(email == null)
				return null;

			email.From = formats.Format(email.From);
			email.Body = formats.Format(email.Body);
			email.Subject = formats.Format(email.Subject);
			email.To = user.Email;
			
            
			string postbody = null;

			// if the user doesn't want HTML and the post is HTML, then strip it
			if (!user.EnableHtmlEmail && post.PostType == PostContentType.HTML) 
				postbody = Emails.FormatHtmlAsPlainText(post.RenderedBody(PostTarget.Other));
			else
				postbody =  post.RenderedBody(PostTarget.Other);
				
			postbody.Trim();

			email.Body = FormatList.Format(email.Body, "postbody", postbody);
		
			return email;
		}

		private static MailMessage CreatFeedbackModerationThresholdNotification(Weblog blog, User user, FormatList formats)
		{

			MailMessage email = GenericEmail("WeblogFeedbackModerationThresholdNotification", user, null, null, false, user.EnableHtmlEmail);

			if (email == null)
				return null;

			email.From = formats.Format(email.From);
			email.Body = formats.Format(email.Body);
			email.Subject = formats.Format(email.Subject);
			email.To = user.Email;

			return email;
		}



	}
}
